<template>
	<div class="incpuser-form">
		<a-modal
			:title="handleType === 'add' ? '增加' : '修改'"
			:visible="visible"
			:confirm-loading="confirmLoading"
			@ok="handleOk"
			@cancel="handleCancel"
		>
			<a-form-model
				ref="incpuserForm"
				:model="form"
				:rules="rules"
				v-bind="layout"
			>
				<!-- v-if="form.marketData.length > 0" -->
				<a-form-model-item label="所属市场">
					<a-select
						v-model="form.market_id"
						style="width: 120px"
						@change="handleMarketChange"
						placeholder="请选择"
					>
						<a-select-option
							v-for="(item, index) in form.marketData"
							:key="index"
							:value="item.id"
						>
							{{ item.name }}
						</a-select-option>
					</a-select>
				</a-form-model-item>
				<a-form-model-item label="场内CP" has-feedback>
					<!-- <a-input-number v-model="form.incp_id" /> -->

					<a-select
						v-model="form.incp_id"
						style="width: 120px"
						@change="handleIncpChange"
						placeholder="请选择"
					>
						<a-select-option
							v-for="(item, index) in form.incpData"
							:key="index"
							:value="item.id"
						>
							{{ item.name }}
						</a-select-option>
					</a-select>
				</a-form-model-item>

				<a-form-model-item label="手机号码" prop="phone" has-feedback>
					<a-input v-model="form.phone" placeholder="请输入" />
				</a-form-model-item>

				<a-form-model-item label="用户名" prop="username" has-feedback>
					<a-input v-model="form.username" placeholder="请输入" />
				</a-form-model-item>

				<a-form-model-item label="头像" prop="avatar" has-feedback>
					<!-- <a-input v-model="form.avatar" /> -->
					<div class="upload-file">
						<div class="avatar-wrapper" v-if="form.avatar">
							<img ref="img" class="avatar" :src="form.avatar" alt="" />
							<span class="delete-icon" @click="removeFile()"
								><img src="@/assets/images/ico_feedback_delete@2x.png" alt=""
							/></span>
						</div>
						<!-- 文件上传按钮 -->
						<a
							href="javascript:void(0)"
							class="upload-icon"
							v-if="!form.avatar"
						>
							<span class="iconfont icon-xiangji"></span>
							<input
								type="file"
								accept="image/*"
								capture="camera"
								id="file"
								name="file"
								@change="uploadFile"
							/>
						</a>
					</div>
				</a-form-model-item>

				<!-- <a-form-model-item label="创建时间" has-feedback>
				<a-date-picker
					format="YYYY-MM-DD HH:mm:ss"
					v-model="form.created_at"
					:show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
				/>
			</a-form-model-item> -->

				<!-- <a-form-model-item label="所属场内CP名称" prop="incp_name" has-feedback>
				<a-input v-model="form.incp_name" />
			</a-form-model-item> -->

				<!-- <a-form-model-item label="所属市场ID" prop="market_id" has-feedback>
				<a-input v-model="form.market_id" />
			</a-form-model-item> -->

				<!-- <a-form-model-item label="所属市场名称" prop="market_name" has-feedback>
				<a-input v-model="form.market_name" />
			</a-form-model-item> -->

				<a-form-model-item label="角色" prop="role_code" has-feedback>
					<app-select
						v-model="form.role_code"
						:code="$e.role"
						radio
						style="width: 100%"
						@change="(data) => (form.role_name = data.area_name_all)"
					/>
				</a-form-model-item>
				<!-- <a-form-model-item label="超级管理员">
        <a-switch
          v-model="form.admin_role"
          checked-children="超级管理员"
          un-checked-children="超级管理员"
        />
      </a-form-model-item> -->

				<a-form-model-item label="状态" has-feedback>
					<a-select
						v-model="form.status"
						style="width: 120px"
						placeholder="请选择"
						@changeStatus="changeStatus(item.key)"
					>
						<a-select-option
							v-for="(item, index) in statusList"
							:key="index"
							:value="item.key"
						>
							{{ item.text }}
						</a-select-option>
					</a-select>
				</a-form-model-item>

				<!-- <a-form-model-item label="更新时间" has-feedback>
				<a-date-picker
					format="YYYY-MM-DD HH:mm:ss"
					v-model="form.updated_at"
					:show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
				/>
			</a-form-model-item> -->

				<!-- <a-form-model-item label="营业结束时间" prop="end_time" has-feedback>
				<a-time-picker
					@change="onChangeEndTime"
					v-model="value2"
					format="HH:mm"
				/>
			</a-form-model-item> -->

				<!-- <a-form-model-item label="用户名" prop="user_name" has-feedback>
				<a-input v-model="form.user_name" />
			</a-form-model-item> -->

				<!-- <a-form-model-item label="所属市场" prop="market_name_show" has-feedback>
				<a-input
					v-model="form.market_name_show"
					:disabled="handleType !== 'add'"
				/>
			</a-form-model-item> -->
				<!-- :disabled="handleType !== 'add'" -->
				<!-- <div slot="footer">
				<a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
					<a-button @cancel="handleCancel"> 取消 </a-button>
					<a-button
						type="primary"
						style="margin-left: 10px"
						@ok="handleOk"
						:disabled="checkRequire(getObj(Object.keys(rules)))"
					>
						确定
					</a-button>
				</a-form-model-item>
			</div> -->
			</a-form-model>
		</a-modal>
	</div>
</template>

<script>
	// import User from "@/api/user"
	import moment from "moment"
	// import momentUtil from "@/utils/day"
	// import Incp from "@/api/incp"
	import IncpUser from "@/api/incpuser"
	import Incp from "@/api/incp"
	import salemarket from "@/api/salemarket"
	import ali_api from "@/api/ali.js"
	const lodash = require("lodash")

	export default {
		name: "HandleForm",
		data() {
			this.id = null
			this.handleType = null
			this.statusList = [
				{
					key: 1,
					text: "正常",
				},
				{
					key: 0,
					text: "停用",
				},
				{
					key: -1,
					text: "冻结",
				},
			]
			return {
				// show: false,
				// avatar: null,

				value1: null,
				value2: null,

				title: "增加",
				layout: {
					labelCol: { span: 6 },
					wrapperCol: { span: 12 },
				},
				ModalText: "Content of the modal",
				visible: false,
				confirmLoading: false,
				form: {
					// 必填
					incp_id: undefined,
					phone: undefined,
					username: undefined,
					// 选填
					avatar: undefined,
					// created_at: "",
					// incp_name: "",
					market_id: undefined,
					// market_name: "",
					status: undefined,
					marketData: [],
					incpData: [],
					// updated_at: "",
				},

				rules: {
					// market_id: [
					// 	{ required: true, trigger: "change", message: "市场ID必填" },
					// ],
					// incp_id: [
					// 	{ required: true, trigger: "change", message: "场内CPID必填" },
					// ],
					phone: [{ required: true, trigger: "change", message: "手机号必填" }],
					username: [
						{ required: true, trigger: "change", message: "用户名必填" },
					],
				},
			}
		},

		watch: {
			visible(newVal) {
				if (newVal == false) {
					this.resetFormFields()
				} else {
					// 获取批发市场列表
					this.getMarketData()
				}
			},
		},
		methods: {
			removeFile() {
				this.form.avatar = ""
				// this.show = false
			},
			uploadFile(e) {
				var event = e || window.event
				var target = event.target || e.srcElement
				var file = target.files[0]

				ali_api.upload(file).then((res) => {
					console.log(res)
					this.form.avatar = res.url
				})
/*
		var formdata = new FormData()
		formdata.append("imgfile", file)
		var url = "http://127.0.0.1:9999/uploadimg"
		fetch(url, {
			// 设定请求方法
			method: "POST",
			headers: {
				// "content-type": "application/json",
			},
			body: formdata,
			// 设定传送的内容
			// body: JSON.stringify({
			// 	userName: "xxf",
			// 	userPwd: "123456",
			// }),
		})
			.then(function (response) {
				// 提取响应对象中的json格式数据
				// 通过response.code == 0判断
				console.log(response)
				return response.text()
			})

			.then((text) => {
				// 管道函数, 接收上一个函数返回的内容
				console.log(JSON.parse(text))
				this.form.avatar = JSON.parse(text).url
			})
			.catch(function (error) {
				// 网络出错或者禁止访问, 404/500无法找到资源不会报错
				console.log(error)
			})
			// this.show = true
*/
			},
			moment,
			handleMarketChange(value) {
				console.log(`selected ${value}`)
				this.form.incp_id = ""
				this.form.market_id = value
				// 获取市场下场内CP列表
				this.getIncp(value)
			},

			handleIncpChange(value) {
				// console.log(value)
				this.form.incp_id = value
			},
			getIncp(market_id = "") {
				console.log(market_id)
				Incp.query({
					market_id,
				})
					.then((res) => {
						console.log(res)
						// this.loading = false
						if (res.code != 1) return
						this.form.incpData = []
						this.form.incpData = res.data.map((item) => {
							return {
								id: item.id,
								name: item.name,
							}
						})

						// this.pagination.total = res.page.totalSize
						// this.pagination.totalPage = res.page.totalPage
						//dataSource 默认将每列数据的 key 属性作为唯一的标识
						//处理数据，否则需要excel代码里处理了
						// this.data = res.data.map((item, index) => {
						// 	return Object.assign(item, { index: index + 1 })
						// })
						// ========================
						// if (this.data.length === 0) {
						// 	this.data = [
						// 		{ id: "1", name: "a" },
						// 		{ id: "2", name: "b" },
						// 	]
						// }
						// ========================
						// console.log(this.data)
					})
					.catch((e) => {
						// this.loading = false
					})
			},
			async getMarketData(params = {}) {
				this.form.marketData = []
				await salemarket.query(params).then((response) => {
					console.log("市场列表数据", response)
					if (response.code !== 1) {
						this.$message.warning(response.message)
						return
					}

					if (response.data && response.data.length > 0) {
						this.form.marketData = response.data.map((item) => {
							return {
								id: item.id,
								name: item.name,
							}
						})
					}
				})
			},
			// onChangeCreatedTime(time, timeString) {
			// 	// this.form.start_time = timeString
			// 	console.log(time, timeString)
			// 	// this.value1 = time
			// },
			onChangeEndTime(time, timeString) {
				this.form.end_time = timeString
				// console.log(time, timeString)
				this.value2 = time
			},
			formatStamp(timeStr) {
				console.log(
					timeStr,
					this.moment(this.$formatDate("h:m", +new Date(timeStr)), "HH:mm")
				)
				return this.moment(this.$formatDate("h:m", +new Date(timeStr)), "HH:mm")
			},
			getObj(rulesKeyArr) {
				let obj = {}
				for (let key of rulesKeyArr) {
					obj[key] = this.form[key]
				}
				return obj
			},
			checkRequire(obj) {
				return this.$isEmpty(obj)
			},

			changeStatus(value) {
				this.form.status = value
			},

			resetFormFields() {
				this.form = {
					// 必填
					incp_id: undefined,
					phone: undefined,
					username: undefined,
					// 选填
					avatar: undefined,
					// created_at: "",
					// incp_name: "",
					market_id: undefined,
					// market_name: "",
					status: undefined,
					marketData: [],
					incpData: [],
					role_code: "",
					// updated_at: "",
				}
				this.value1 = null
				this.value2 = null
				// this.show = false
				this.$refs.incpuserForm.resetFields()
			},

			handleOk() {
				this.handleType === "add" ? this.addIncpUser() : this.updateIncpUser()
			},
			addIncpUser() {
				let _this = this

				// _this.form.created_at._d = this.$standardDateToTimstamp(
				// 	_this.form.created_at._d
				// )

				// _this.form.updated_at._d = this.$standardDateToTimstamp(
				// 	_this.form.updated_at._d
				// )
				_this.$refs.incpuserForm.validate((err, values) => {
					// 验证表单没错误
					if (err) {
						_this.confirmLoading = true
						IncpUser.create(
							this.$removeField(
								// ..._this.form,
								lodash.omit(_this.form, ["marketData", "incpData"])
								// created_at: this.$standardDateToTimstamp(
								// 	_this.form.created_at._d
								// ),
								// updated_at: this.$standardDateToTimstamp(
								// 	_this.form.updated_at._d
								// ),
							)
						)
							.then((res) => {
								_this.confirmLoading = false
								if (res.code == 1) {
									_this.$message.success("添加成功")
									_this.$emit("handleOk")
									setTimeout(() => {
										_this.visible = false
									}, 500)
								}
							})
							.catch((e) => {
								_this.confirmLoading = false
							})
					}
				})
			},

			updateIncpUser() {
				let _this = this
				_this.$refs.incpuserForm.validate((err, values) => {
					// 验证表单没错误
					if (err) {
						_this.confirmLoading = true
						IncpUser.update(
							_this.form.id,
							this.$removeField(
								lodash.omit(_this.form, ["marketData", "incpData"])
							)
						)
							.then((res) => {
								_this.confirmLoading = false
								if (res.code == 1) {
									_this.$message.success("修改成功")
									_this.$emit("handleOk")
									setTimeout(() => {
										_this.visible = false
									}, 500)
								}
							})
							.catch((e) => {
								_this.confirmLoading = false
							})
					}
				})
			},
			// getIncpDetail(id) {
			// 	IncpUser.select(id).then((res) => {
			// 		console.log("场内cp详情", res)
			// 		// if (res.code == 1) {
			// 		// }
			// 	})
			// },
			showModal(type, record) {
				console.log(type, record)
				this.handleType = type
				if (type === "update") {
					this.form = {
						role_code: record.role_code,
						id: record.id,
						avatar: record.avatar,
						incp_id: record.incp_id,
						market_id: record.market_id,
						phone: record.phone,
						username: record.username,
						status: record.status,
						marketData: [],
						incpData: [],
					}
					// this.show = true

					this.getMarketData()
					this.getIncp(record.market_id)

					// Object.keys(this.form).forEach((key) => {
					// 	this.form[key] = recode[key]
					// })
					// this.id = recode.id
					// // ====================页面显示数据============================
					// this.value1 =
					// 	this.form.start_time.length <= 5
					// 		? this.moment(this.form.start_time, "HH:mm")
					// 		: this.formatStamp(this.form.start_time)
					// this.value2 =
					// 	this.form.end_time.length <= 5
					// 		? this.moment(this.form.end_time, "HH:mm")
					// 		: this.formatStamp(this.form.end_time)
					// // ====================传递到后端数据============================
					// this.form.start_time =
					// 	this.form.start_time.length <= 5
					// 		? this.form.start_time
					// 		: this.$formatDate("h:m", +new Date(this.form.start_time))
					// this.form.end_time =
					// 	this.form.end_time.length <= 5
					// 		? this.form.end_time
					// 		: this.$formatDate("h:m", +new Date(this.form.end_time))

					// this.getIncpDetail(recode.id)
				} else if (type === "add") {
					// this.$refs.incpuserForm.resetFields()
				}
				this.visible = true
			},

			handleCancel(e) {
				this.visible = false
			},
		},
	}
</script>

<style lang='less' scoped>
	// .incpuser-form {
	.upload-file {
		margin-left: 5px;
		.avatar-wrapper {
			width: 100px;
			height: 100px;
			position: relative;
			.avatar {
				width: 100%;
				height: 100%;
			}
			.delete-icon {
				position: absolute;
				right: -8px;
				top: -8px;
				width: 18px;
				height: 18px;
				line-height: 18px;
				text-align: center;
				cursor: pointer;
				img {
					width: 100%;
					height: 100%;
				}
			}
		}
		.upload-icon {
			border: 1px solid rgba(0, 0, 0, 0.2);
			position: relative;
			left: 0;
			display: inline-block;
			color: #fff;
			text-decoration: none;
			width: 100px;
			height: 100px;
			line-height: 100px;
			text-align: center;
			.icon-xiangji {
				font-size: 28px;
				color: #333;
				margin-right: 0;
			}
			#file {
				opacity: 0;
				width: 100%;
				height: 100%;
				position: absolute;
				left: 0;
				top: 0;
			}
		}
	}
	// }
</style>
